<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

/**
 * @author Anh Nguyen <duyanhnguyen@vccorp.vn>
 * @copyright 2012
 */
class Post extends MX_Controller
{

    private $_langCode;

    function __construct()
    {
        parent::__construct();
        $this->load->library('Layout');
        $this->_langCode = $this->mycommon->getLangCode();
    }

    public function index($id = '')
    {
        $data = array();
        if ($id == '' || intval($id) == 0)
            show_404();
        $this->load->model('post/post_model');
        $this->load->library('Minifier');
        $this->load->language('landing/landing', $this->_langCode);
        $langCode = $this->mycommon->fetchLangCode($this->_langCode);
        $tmpInfo = $this->post_model->getInfoById($id, $langCode);
        if (!$tmpInfo) {
            show_404();
        } else {
            $this->layout->setMenuActive($tmpInfo[0]['parent_id']);
            if ($this->session->userdata('post_voted')) {
                $voted = $this->session->userdata('post_voted');
                if (in_array($id, $voted)) {
                    $data['voted'] = true;
                } else {
                    $data['voted'] = false;
                }
            } else {
                $data['voted'] = false;
            }
            $data['postInfo'] = $tmpInfo[0];
            $tmpMorePost = $this->post_model->getMorePostWithType($id, $tmpInfo[0]['type'], $langCode);
            $data['lang'] = $this->lang->line('landing_lang');
            $data['headTitle'] = $tmpInfo['0']['title'];
            $data['morePost'] = $tmpMorePost;
        }
        $this->minifier->AddCss('jRating.jquery');
        $this->minifier->AddSharedJsNoPack('jRating.jquery.min');
        $this->layout->view('post/product_detail_view', $data);
    }

    public function vote()
    {
        $data = array();
        $action = $this->input->post('action');
        $idBox = $this->input->post('idBox');
        $vote = $this->input->post('rate');
        if ($action == '' || $idBox == '' || $vote == '' || $action != 'rating') {
            $data['error'] = true;
        } else {
            $this->load->model('post/post_model');
            $rs = $this->post_model->votePost($idBox, $vote);
            if ($rs) {
                if ($this->session->userdata('post_voted')) {
                    $voted = array();
                    $voted = $this->session->userdata('post_voted');
                    array_push($voted, $idBox);
                    $this->session->set_userdata('post_voted', $voted);
                } else {
                    $voted = array($idBox);
                    $this->session->set_userdata('post_voted', $voted);
                }
                $data['error'] = false;
                $data['count'] = $rs[0]['count_vote'];
            } else {
                $data['error'] = true;
            }
        }
        echo json_encode($data);
    }

}

?>
